package com.example.codeloginjava.websocket;

import com.alibaba.fastjson.JSONObject;
import com.example.codeloginjava.mode.WebSocketModel;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoginWebSocketServer implements WebSocketHandler {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketSession对象,目前仅支持一个账号登录一个客户端
    private static ConcurrentHashMap<String, WebSocketSession> sessionPools = new ConcurrentHashMap<>();

    // 获取当前用户
    private String getUserName(WebSocketSession webSocketSession) {
        URI uri = webSocketSession.getUri();
        String path = uri.getPath();
        String userName = path.substring(path.lastIndexOf("/")+1);
        return userName;
    }

    // 建立连接时调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = getUserName(session);
        sessionPools.put(username, session);
    }

    // 处理收到消息
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if(!message.getPayload().equals("heart")) {
            String s = JSONObject.toJSONString(message.getPayload().toString());
            String parse = (String) JSONObject.parse(s);
            JSONObject object = (JSONObject) JSONObject.parse(parse);
            String to = (String) object.get("to");
            Map<String, Boolean> map = new HashMap<>();
            map.put("isCode", (Boolean) object.get("isCode"));
            WebSocketModel<Map<String, Boolean>> webSocketModel = new WebSocketModel();
            webSocketModel.setDate(new Date());
            webSocketModel.setMessage("success");
            webSocketModel.setData(map);
            webSocketModel.setCode(101);
            TextMessage textMessage = new TextMessage(JSONObject.toJSONString(webSocketModel));
            sendInfo(to, textMessage);
        }

    }

    // 发生错误时调用
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    // 关闭连接时调用
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        sessionPools.remove(getUserName(session));
    }

    // 群发消息
    public void broadcast(WebSocketMessage message){
        //获取当前所有连接，遍历循环
        for (WebSocketSession session: sessionPools.values()) {
            try {
                //发送消息
                sendMessage(session, message);

            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //发送消息
    public void sendMessage(WebSocketSession session, WebSocketMessage message) throws IOException {
        if(session != null){
            synchronized (session) {
                System.out.println("发送数据：" + message);
                session.sendMessage(message);
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userName, WebSocketMessage message){
        WebSocketSession session = sessionPools.get(userName);
        System.err.println(session);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //人数增加1
    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }
    //人数减1
    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
    //获取当前在线人数
    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }
    //获取当前session线程池
    public static ConcurrentHashMap<String, WebSocketSession> getSessionPools() {
        return sessionPools;
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
